﻿using System.Diagnostics.Contracts;
using System.IO;

namespace OpenLS.Spreadsheet.Formats.Biff.Records
{
    internal struct DXFFntD
    {
        private Stxp Stxp;
        private int cch;
        private bool fBlsNinch;
        private bool fSssNinch;
        private bool fUlsNinch;
        private ushort iFnt;
        private int ich;
        private uint icvFore;
        private XLUnicodeStringNoCch stFontName;
        private Ts ts;
        private byte[] unused;
        private uint unused2;

        internal string FontName
        {
            get { return (string) stFontName; }
        }

        public void Read(BinaryReader reader)
        {
#if DEBUG
            ReadWriteChecker.CheckStruct((ref DXFFntD t, BinaryReader r) => t.Read(r),
                                         (ref DXFFntD t, BinaryWriter w) => t.Write(w), reader, ref this);
#endif
            byte cchFont = reader.ReadByte();
            long position = reader.BaseStream.Position;
            stFontName.Read(reader, cchFont);
            Contract.Assert(((string) stFontName) != null);
            unused = new byte[0];
            if (reader.BaseStream.Position < position + 63)
                unused = reader.ReadBytes((int) (position + 63 - reader.BaseStream.Position));
            //            reader.BaseStream.Position = position + 63;
            Stxp.Read(reader);
            icvFore = reader.ReadUInt32();
            reader.ReadUInt32();
            ts.Read(reader);
            fSssNinch = reader.ReadUInt32() != 0;
            fUlsNinch = reader.ReadUInt32() != 0;
            fBlsNinch = reader.ReadUInt32() != 0;
            unused2 = reader.ReadUInt32();
            ich = reader.ReadInt32();
            cch = reader.ReadInt32();
            iFnt = reader.ReadUInt16();
        }

        public void Write(BinaryWriter writer)
        {
            Contract.Requires(FontName != null);
            Contract.Assert((string) stFontName != null);
            writer.Write((byte) ((string)stFontName).Length);
            long position = writer.BaseStream.Position;
            stFontName.Write(writer);
            if (unused != null)
                writer.Write(unused);
            writer.BaseStream.Position = position + 63;
            Stxp.Write(writer);
            writer.Write(icvFore);
            writer.Write((uint) 0);
            ts.Write(writer);
            writer.Write(BoolToUint32(fSssNinch));
            writer.Write(BoolToUint32(fUlsNinch));
            writer.Write(BoolToUint32(fBlsNinch));
            writer.Write(unused2);
            writer.Write(ich);
            writer.Write(cch);
            writer.Write(iFnt);
        }

        private static uint BoolToUint32(bool b)
        {
            if (b)
                return 1;
            return 0;
        }
    }
}